package me.idashu.attg.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import me.idashu.attg.domain.PageEntity;
import me.idashu.attg.domain.UserEntity;
import me.idashu.attg.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	/**
	 * 查询用户列表公共的方法
	 * @param pageEntity
	 * @param userEntity
	 * @param request
	 * @param model
	 */

	@RequestMapping(value = "/getUsers")
	public String getUsers(@ModelAttribute PageEntity pageEntity,
			Model model) {
		selectUsers(pageEntity, model);
		model.addAttribute("userList", "用户列表");
		return "user_list";
	}
	
	@RequestMapping(value = "/userAjaxList")
	public String userAjaxList(@ModelAttribute PageEntity pageEntity,
			Model model) {
		selectUsers(pageEntity, model);
		model.addAttribute("userList", "用户列表");
		return "userAjaxList";
	}
	
	private void selectUsers(PageEntity pageEntity,Model model){
		Map<String,Object> map = new HashMap<String, Object>();
		UserEntity userEntity = new UserEntity();
		int count = userService.findCountUsersByPage(userEntity);
		pageEntity.setTotalPage(count);
		pageEntity.setPageLess(pageEntity.getPage());
		map.put("pageEntity", pageEntity);
		map.put("userEntity", userEntity);
		List<UserEntity> users = userService.findUsersByPage(map);
		if(users !=null &&users.size()>0){
			model.addAttribute("users", users);
		}else{
			model.addAttribute("users", null);
		}
	}

	@RequestMapping(value = "/web/adduser")
	public String preAddUser(Locale locale, Model model) {
		model.addAttribute("adduser", "添加用户");
		return "add_admin";
	}

	/**
	 * 验证页面输入的用户名是否存在
	 * 
	 * @param userName
	 * @param response
	 */
//	@RequestMapping(value = "/web/checkUserName")
//	public void preCheckUserName(@RequestParam("username") String userName,
//			HttpServletResponse response) {
//		response.setContentType("text/html;charset=GBK");
//		try {
//			String checkResult = null;
//			userName = Escape.unescape(userName);
//			int count = userService.getCountByUserName(userName);
//			if (count > 0) {
//				checkResult = "1";
//			} else {
//				checkResult = "0";
//			}
//			response.getWriter().print(checkResult);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

	@RequestMapping(value = "/web/login")
	public String preLogin(Locale locale, Model model) {
		return "user/login";
	}
	
}
